package com.kfc.platform.framework.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

public abstract class BaseDaoImpl<T> implements BaseDao<T> {
    @PersistenceContext
    protected EntityManager entityManager;
    private Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    public void save(T entity) {
//          entityManager.persist(entity);
    	Session s = this.getSession();
        s.save(entity);
//        getSession().getTransaction().commit();
    }

    @Override
    public void delete(T entity) {
        entityManager.remove(entity);
        entityManager.flush();
        entityManager.clear();
//    	Session s = this.getSession();
//        s.delete(entity);
//        s.getTransaction().commit();
    }

    @Override
    public void update(T entity) {
//    	entityManager.setFlushMode(FlushModeType.COMMIT);
        entityManager.merge(entity);
//        System.out.println("from update："+entityManager.getClass());
        entityManager.flush();
        entityManager.clear();
//    	Session s = this.getSession();
//    	s.beginTransaction();
//    	s.update(entity);
//    	s.getTransaction().commit();
//    	s.getTransaction().commit();
    }

    @Override
    public T findById(Object id) {
    	//System.out.println("from find："+entityManager.getClass());
        return (T)getSession().get(clazz, (Serializable)id);
        		//entityManager.find(clazz, id);
    }

    @Override
    public List<T> findAll() {
        return this.getSession().createQuery("from "+clazz.getName()).list();
    }
    
    protected Session getSession() {
//        return (Session) entityManager.getDelegate();
        return entityManager.unwrap(Session.class);
    }

    protected Criteria createCriteria(){
        return this.getSession().createCriteria(clazz);
    }
}
